﻿using System.Collections.Generic;
using System.Linq;
using UnityEngine;

namespace Assets.Scripts
{
	[RequireComponent(typeof(Rigidbody))]
	class Moon2 : MonoBehaviour
	{
		private List<Rigidbody> rigidbodies = new List<Rigidbody>();
		private Rigidbody m_Rigidbody;

		private List<float> distances = new List<float>();
		[SerializeField]
		private float speed;
		[SerializeField]
		private float forceScale = 1;

		[Header("Debug 用"), SerializeField]
		private float froce = 1;
		[SerializeField]
		private float velocityScale = 1;

		private void Start()
		{
			var temp = FindObjectsOfType<Rigidbody>().ToList();
			foreach (var item in temp)
			{
				if (item.gameObject != gameObject)
				{
					rigidbodies.Add(item);
				}
			}

			//distance = Vector3.Distance(transform.position, Earth.position);
			foreach (var item in rigidbodies)
			{
				distances.Add(Vector3.Distance(transform.position, item.position));
			}

			Vector3 v = new Vector3(Random.Range(-1.0f, 1), Random.Range(-1.0f, 1), Random.Range(-1.0f, 1));
			m_Rigidbody = GetComponent<Rigidbody>();
			m_Rigidbody.mass = transform.localScale.x;
			m_Rigidbody.velocity = v.normalized * speed;
		}

		private void FixedUpdate()
		{
			//Vector3 froce = (Earth.position - transform.position).normalized * 1 / distance * forceScale;
			//rigidbody.AddForce(froce);
			Vector3 resultantForce = Vector3.zero;
			Vector3 temp;
			for (int i = 0; i < rigidbodies.Count; i++)
			{
				temp = CalculateFroce(rigidbodies[i].position, distances[i]);
				resultantForce += temp;
				Debug.DrawRay(transform.position, temp);
			}

			Debug.DrawRay(transform.position, m_Rigidbody.velocity * velocityScale, Color.red);
			m_Rigidbody.AddForce(resultantForce);
		}

		private Vector3 CalculateFroce(Vector3 targetPosition, float distance)
		{
			return (targetPosition - transform.position).normalized * 1 / distance * forceScale;
		}
	}
}
